package com.wpen.unit.utils;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * 获取运行环境数据
 * 
 * @author pg
 * 
 */
public class EnvironmentUtil {
    private static final String ANYHOST_VALUE = "0.0.0.0";
    private static final String LOCALHOST_VALUE = "127.0.0.1";
    private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");

    /**
     * 获取JDK名称
     * 
     * @return
     */
    public static String getJdkName() {
        Properties props = System.getProperties();
        return props.getProperty("java.vm.name");
    }

    /**
     * 获取JDK版本信息
     * 
     * @return
     */
    public static String getJdkVersion() {
        Properties props = System.getProperties();
        return props.getProperty("java.runtime.version");
    }

    /**
     * 获取操作系统名称
     * 
     * @return
     */
    public static String getOSName() {
        Properties props = System.getProperties();
        return props.getProperty("os.name");
    }

    /**
     * 获取操作系统
     * 
     * @return
     */
    public static String getOS() {
        Map<String, String> map = System.getenv();
        return map.get("OS");
    }

    /**
     * 获取系统用户临时文件目录
     * 
     * @return
     */
    public static String getTempPath() {
        Map<String, String> map = System.getenv();
        String temp = map.get("TEMP");
        if (temp == null || "".equals(temp)) {
            temp = map.get("TMP");
        }
        return temp;
    }

    /**
     * 获取机器主机名
     * 
     * @return
     */
    public static String getHostName() {
        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            if (hostName == null || "".equals(hostName)) {
                Map<String, String> map = System.getenv();
                return map.get("COMPUTERNAME"); // 计算机名
            }
            return hostName;
        } catch (UnknownHostException e) {
            Map<String, String> map = System.getenv();
            String hostName = map.get("COMPUTERNAME");
            if (hostName == null || "".equals(hostName)) {
                e.printStackTrace();
            } else {
                return hostName;
            }
        }
        return null;
    }

    /**
     * 获取服务器的ip地址
     * 
     * @return
     */
    public static List<InetAddress> getIpAddress() {
        return getIpAddress(null);
    }

    public static List<InetAddress> getIpAddress(String networkName) {
        List<InetAddress> addressRses = new ArrayList<>();
        if (networkName == null || "".equals(networkName)) {
            try {
                InetAddress localAddress = InetAddress.getLocalHost();
                InetAddress addressItem = toValidAddress(localAddress);
                if (addressItem != null) {
                    addressRses.add(addressItem);
                    return addressRses;
                }
            } catch (Throwable e) {
                // ignore
            }
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (null == interfaces) {
                return null;
            }
            while (interfaces.hasMoreElements()) {
                try {
                    NetworkInterface network = interfaces.nextElement();
                    if (network.isLoopback() || network.isVirtual() || !network.isUp()) {
                        continue;
                    }
                    if (networkName != null && !"".equals(networkName) && !networkName.equals(network.getName())) {
                        continue;
                    }
                    Enumeration<InetAddress> addresses = network.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        try {
                            InetAddress addressItem = toValidAddress(addresses.nextElement());
                            if (addressItem != null) {
                                try {
                                    if (addressItem.isReachable(100)) {
                                        addressRses.add(addressItem);
                                    }
                                } catch (IOException e) {
                                    // ignore
                                }
                            }
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return addressRses;
    }

    private static InetAddress toValidAddress(InetAddress address) {
        if (address instanceof Inet6Address) {
            Inet6Address v6Address = (Inet6Address) address;
            if (isPreferIPV6Address()) {
                return normalizeV6Address(v6Address);
            }
        }
        if (isValidV4Address(address)) {
            return address;
        }
        return null;
    }

    private static boolean isPreferIPV6Address() {
        return Boolean.getBoolean("java.net.preferIPv6Addresses");
    }

    private static boolean isValidV4Address(InetAddress address) {
        if (address == null || address.isLoopbackAddress()) {
            return false;
        }
        String name = address.getHostAddress();
        boolean result = (name != null && IP_PATTERN.matcher(name).matches() && !ANYHOST_VALUE.equals(name)
                && !LOCALHOST_VALUE.equals(name));
        return result;
    }

    private static InetAddress normalizeV6Address(Inet6Address address) {
        String addr = address.getHostAddress();
        int i = addr.lastIndexOf('%');
        if (i > 0) {
            try {
                return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId());
            } catch (UnknownHostException e) {
                // ignore
            }
        }
        return address;
    }

    public static void main(String[] args) {
        System.out.println(getIpAddress("wlan2"));
        System.out.println(getHostName());
        System.out.println(getJdkName());
        System.out.println(getJdkVersion());
        System.out.println(getOS());
        System.out.println(getOSName());
        System.out.println(getTempPath());
    }
}
